<?php
if ( !defined('IN_ADMINCP') || !defined('IN_SEC') ){
	exit('Access Denied.');
}
//$admincp->addmenu('edit', '添加管理员');
$id = intval(trim($_G['gp_id']));
$companyid = intval(abs($_G['gp_companyid']));
$departmentid = intval(abs($_G['gp_departmentid']));
//如果传入$id，则检测管理员是否存在，不存在提示错误
if ( $id ){
	if ( !$admin = fetch('admincp_member', $id) ){
		$admincp->cpmsg('管理员不存在');
	}
	//如果存在管理员，编辑菜单
	$admincp->editmenu('edit', '编辑管理员');
	if ( $admincp->admin['id'] != $admin['id'] ){
		//禁止编辑系统最高管理员
		if ( $admin['id'] == 1 ){
			$admincp->cpmsg('禁止编辑系统最高管理员');
		}
		//禁止编辑系统管理员
		if ( $admin['founder'] && !$admincp->founder ){
			$admincp->cpmsg('无权编辑系统管理员');
		}
		//禁止编辑等级比自己高或者同级的管理员
		if ( $admincp->groups[$admin['groupid']]['rank'] >= $admincp->admin['group']['rank'] ){
			$admincp->cpmsg('您的等级无法更改该管理员');
		}
	}
}
$companys = limitquery('companys');

$depart_where = array();

$depart_where_companyid = $admin['companyid'] ? $admin['companyid'] : $companys[0]['id'];
$depart_where_companyid = $companyid ? $companyid : $depart_where_companyid;
$depart_where_companyid = $depart_where_companyid ? $depart_where_companyid : 0;

if( $depart_where_companyid ){
	$depart_where[] = "`companyid` = 0 OR `companyid` = {$depart_where_companyid}";
}else{
	$depart_where['companyid'] = 0;
}

$departments = limitquery('admincp_department', $depart_where);

$group_where = array();
$group_where_departmentid = $admin['departmentid'] ? $admin['departmentid'] : $departments[0]['id'];
$group_where_departmentid = $departmentid ? $departmentid : $group_where_departmentid;
$group_where_departmentid = $group_where_departmentid ? $group_where_departmentid : 0;

if( $admin['id'] != 1 ){
	$group_where[] = '`id` != 1';	
}

if( $group_where_departmentid ){
	$group_where[] = "`departmentid` = 0 OR `departmentid` = {$group_where_departmentid}";
}else{
	$group_where['departmentid'] = 0;
}

//获取系统分组
$groups = limitquery('admincp_group', $group_where);

$departments = parse_array($departments);


if ( is_post() ){
	if( !confirm_password($admincp->admin) ){
		$admincp->cpmsg('密码不正确！授权操作失败！');
	}

	$groupid = intval($_G['gp_groupid']);
	$account = new admincp_account();
	if ( $admin ){
		if ( $groupid ){
			//如果存在$groupid，判断是否存在所选分组，该结果从缓存内读取
			if ( $admincp->admin['group'][$groupid] ){
				//如果存在所选分组，判断当前管理员所在分组是否相等，判断所选分组等级是否小于所在分组
				if ( $admincp->admin['group']['rank'] != $admincp->admin['group'][$admin['groupid']] && $admincp->admin['group'][$groupid]['rank'] < $admincp->admin['group']['rank'] ){
					$admin['groupid'] = $groupid;
				}else{
					$admincp->cpmsg('您不能更改您的职位');
				}
			}
		}
		if( $admin['id'] != 1 ){
			$admin['departmentid'] = $departmentid;
			$admin['companyid'] = $companyid;
		}
		$admin['mobile'] = $_G['gp_phone'];
		$update = $account->edit($admin);
	}else{
		$update = $account->register();
	}
	$admincp->success();
}

?>